package com.bw.permission.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.permission.config.AjaxResult;
import com.bw.permission.entity.Menu;
import com.bw.permission.entity.Role;
import com.bw.permission.entity.RoleMenu;
import com.bw.permission.entity.UserRole;
import com.bw.permission.service.*;
import com.bw.permission.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2020-10-28
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService iRoleService;
    
    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IRoleMenuService iRoleMenuService;
    
    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private IUserService iUserService;
    @GetMapping("list")
    public AjaxResult list(Role role, Page page){
        //查询条件
        QueryWrapper queryWrapper = new QueryWrapper();
        if(role.getName()!=null){
            queryWrapper.like("name",role.getName());
        }
        //查询数据
        IPage<Role> pageInfo = iRoleService.page(page,queryWrapper);
        return AjaxResult.ok(pageInfo);
    }

    @PostMapping("save")
    public AjaxResult save(@RequestBody Role role){
        if(!jwtUtils.isRole("promanager")){
            return AjaxResult.err(600, "没有修改权限");
        }
        //
        if (role.getId() == null) {
            role.setCreated(LocalDateTime.now());
        }
        iRoleService.saveOrUpdate(role);
        return AjaxResult.ok();
    }

    @GetMapping("allRoleList")
    public AjaxResult allRoleList(){
        List<Role> list = iRoleService.list();
        return AjaxResult.ok(list);
    }
    @GetMapping("getRoleIdsByUserId")
    public AjaxResult getRoleIdsByUserId(Integer userId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("uid",userId);
        List<UserRole> list = iUserRoleService.list(queryWrapper);
        List<Integer> roleIdList = list.stream().map(ur -> ur.getRid()).collect(Collectors.toList());
        return AjaxResult.ok(roleIdList);
    }

    /**
     * 绑定菜单
     * @param role
     * @return
     */
    @PostMapping("bindMenu")
    @Transactional
    public AjaxResult bindMenu(@RequestBody Role role){
        //删除关系表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("rid",role.getId());
        iRoleMenuService.remove(queryWrapper);
       
        //检查二级菜单Id，是否存在它的父菜单Id
        List<Integer> menuIds = role.getMenuIds();
        //查询菜单，取parentId转化成set，需要处理parentId=0的数据
        List<Menu> menus = iMenuService.listByIds(menuIds);
        Set<Integer> menuIdSet = menus.stream().map(m -> m.getParentId()).collect(Collectors.toSet());
        menuIdSet.addAll(menuIds);
        //插入关系表
        if(menuIdSet!=null){
            menuIdSet.forEach(menuId->{
                if(menuId>0){
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setRid(role.getId());
                    roleMenu.setMid(menuId);
                    iRoleMenuService.save(roleMenu);
                }
            });
        }
        return  AjaxResult.ok(null);
    }
}
